package cn.daniellee.plugin.pm.runnable;

import cn.daniellee.plugin.pm.PartnerMission;
import cn.daniellee.plugin.pm.core.MissionCore;
import cn.daniellee.plugin.pm.model.Invite;
import cn.daniellee.plugin.pm.model.Mission;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.*;

public class MissionRunnable extends BukkitRunnable {

    @Override
    public void run() {
        long now = System.currentTimeMillis();
        // 遍历邀请
        Iterator<Invite> inviteIterator = MissionCore.invites.iterator();
        while (inviteIterator.hasNext()) {
            Invite invite = inviteIterator.next();
            if (invite.getValidUntil() < now) {
                Player player = Bukkit.getPlayer(invite.getInviter());
                if (player != null) player.sendMessage((PartnerMission.getInstance().getPrefix() + PartnerMission.getInstance().getConfig().getString("message.invite-timeout", "&eYour invitation to &b{invitee} &ehas expired.").replace("{invitee}", invite.getInvitee())).replace("&", "§"));
                inviteIterator.remove();
            }
        }
        // 遍历任务
        Iterator<Mission> missionIterator = MissionCore.missions.iterator();
        while (missionIterator.hasNext()) {
            Mission mission = missionIterator.next();
            if (mission.getProgress() != 5 && mission.getValidUntil() < now) {
                MissionCore.sendMessageBoth(mission, (PartnerMission.getInstance().getPrefix() + PartnerMission.getInstance().getConfig().getString("message.mission-timeout", "&eThe task has been cancelled due to timeout, please re-invite partners.")).replace("&", "§"));
                missionIterator.remove();
            }
        }
        // 遍历在线玩家
        MissionCore.onlines.forEach(online -> {
            if (online.getCurrentCount() == 60) {
                online.setCurrentCount(0);
                online.setOriginMinutes(online.getOriginMinutes() + 1);
                Map<String, Object> fields = new HashMap<>();
                fields.put("online_minutes", online.getOriginMinutes());
                PartnerMission.getInstance().getStorage().updatePlayer(online.getName(), fields);
            } else online.setCurrentCount(online.getCurrentCount() + 1);
        });
    }
}
